<!--
机器人编辑
-->
<template>
  <div class="robot-manage">
    <div class="robot-manage-title">新建/编辑机器人</div>
    <section v-loading="loading" class="robot-manage-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="form"
      >
        <el-form-item label="机器人名称" prop="robotName">
          <el-input v-model="form.robotName" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="机器人头像" required>
          <image-upload
            :key="uploadFile.imagecropperKey"
            v-model="form.robotPortrait"
            :preview-id="form.robotPortrait"
            :forever="true"
            :width="150"
            :view="uploadFile.view"
            :height="150"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <el-form-item label="机器人等级" prop="robotLevel">
          <el-radio-group v-model="form.robotLevel">
            <el-radio
              v-for="(item, index) in dict.PKROBOT"
              :key="index"
              :label="item.dictValue"
            >{{ item.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答题速度" required>
          <el-input v-model.number="form.speedStart" style="width:30%" placeholder="请输入每题作答速度(秒)" />&nbsp; <span>至</span>&nbsp;<el-input v-model.number="form.speedEnd" style="width:30%" placeholder="请输入每题作答速度(秒)" />
        </el-form-item>
        <el-form-item label="正确率" prop="correctRate">
          <el-input
            v-model.number="form.correctRate"
            placeholder="请输入正确率"
          />
        </el-form-item>
      </el-form>
    </section>
    <section class="robot-manage-footer">
      <el-button
        style="padding: 10px 30px"
        @click="
          () => {
            $router.back();
          }
        "
      >取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'

import {
  getDictByCode,
  insert,
  update,
  get
} from '../api/index'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  name: 'RobotManage',
  components: { ImageUpload },
  directives: { elDragDialog },
  data() {
    return {
      loading: false,
      form: {
        id: '',
        correctRate: '',
        speedStart: '',
        speedEnd: '',
        robotLevel: '',
        robotPortrait: '',
        robotName: '',
        fkInfoId: ''
      },
      rules: {
        correctRate: [
          { required: true, message: '请输入正确率', trigger: 'blur' }
        ],
        robotLevel: [
          {
            required: true,
            message: '请选择机器人等级',
            trigger: 'blur'
          }
        ],
        robotName: [
          { required: true, message: '请输入机器人名称', trigger: 'blur' }
        ],
        robotPortrait: [
          { required: true, message: '请上传机器人头像', trigger: 'change' }
        ]
      },
      state: 'create',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: false,
        accept: '',
        fileType: '',
        fileIndex: 0
      },
      dict: {
        PKROBOT: []
      }
      // gradeList: [
      //   {
      //     dictName: '容易',
      //     dictValue: 'PK_ROBOT_LEVEL1'
      //   },
      //   {
      //     dictName: '正常',
      //     dictValue: 'PK_ROBOT_LEVEL2'
      //   },
      //   {
      //     dictName: '较难',
      //     dictValue: 'PK_ROBOT_LEVEL3'
      //   },
      //   {
      //     dictName: '超难',
      //     dictValue: 'PK_ROBOT_LEVEL4'
      //   }
      // ]
    }
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
        return
      }
      this.getData(this.$route.query.i)
    } else {
      this.form.fkInfoId = this.$route.query.fkInfoId
    }
  },
  methods: {
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] =
                  res.data.data && res.data.data.length > 0
                    ? res.data.data[0].list
                    : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    CleanPastedHTML(input) {
      if (!input) {
        return ''
      }
      input = input.replace(/<\/?[^>]*>/g, '') // 去除HTML tag
      input = input.replace(/(\r)/gi, '')
      input = input.replace(/(\n)/gi, '')
      input = input.replace(/(\t)/gi, '')
      input = input.replace(/ /gi, '') // 去掉
      return input.replace(/&(.*?);/gi, '')
    },

    isEmpty(e) {
      if (e.target.value === '') {
        this.$message({
          message: '附件名称不能为空！',
          type: 'warning'
        })
      }
    },
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const params = Object.assign({}, this.form)
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.back()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const params = Object.assign({}, this.form)
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.back()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              this.form[key] = data[key]
            }
            this.uploadFile.viewId = data.coverImgId
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'y+': date.getFullYear().toString(), // 年
        'M+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'm+': date.getMinutes().toString(), // 分
        's+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.robot-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .robot-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .robot-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
    .form {
      width: 1000px !important;
      margin: 0 auto;
      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }
    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;
      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }
    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }
    .vote-image {
      .el-card__header {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }
    .images-item {
      position: relative;
      margin-bottom: 10px;
      .upload-img {
        width: 100%;
        height: 160px;
        display: block;
      }
      .el-input {
        display: block;
      }
      .custom-uploader {
        width: 100%;
        display: block;
        .icon-wrap {
          width: 100%;
          height: 160px;
        }
      }
      .el-button {
        position: absolute;
        right: 10px;
        top: 0;
        color: #fff;
        i {
          background: rgba(0, 0, 0, 0.4);
          border-radius: 50%;
          padding: 2px;
        }
        &.image-index-move {
          right: 40px;
        }
      }
    }
    .images-add {
      color: $mainColor;
      font-size: 14px;
      padding-left: 80px;
      cursor: pointer;
      margin-bottom: 20px;
    }
    .upload-img {
      width: 100%;
      height: 160px;
    }
    .attachment-item {
      margin-bottom: 10px;
      .item-btn {
        font-size: 20px;
        cursor: pointer;
      }
      .video-item {
        position: relative;
        cursor: pointer;
        .el-button {
          position: absolute;
          right: 10px;
          top: 0;
          color: #fff;
          i {
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            padding: 2px;
          }
          &.video-index-move {
            right: 40px;
          }
        }
      }
    }
  }

  .robot-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;
      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }
   /* .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }*/
  }
}
</style>
<style lang="scss">
.robot-manage {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;
    .classify-tree-con-scrollbar {
      overflow: hidden;
      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }
    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;
      .tree-node-txt {
        flex: 1;
      }
    }
  }
  .el-tag--medium {
    line-height: 32px;
    height: 32px;
    & + .el-tag--medium {
      margin-left: 10px;
    }
  }
}
</style>
